#include <iostream>
#include <unistd.h>
#include <fstream>
#include <string>
#include <mysql/mysql.h>
#include <cstring>
#include <errno.h>


int main()
{
    std::string methon = getenv("METHOD");
    std::string paramenter; //CGI 获取目标文章的主键，这里就只有目标文章的主键

    int post_length = 0;
    if (methon == "GET")
    {
        paramenter = getenv("PARAMENTER");
    }else if (methon == "POST")
    {
        //1.获取先出发来CGI的参数信息
        post_length = atoi(getenv("CONTENT-LENHTH"));
        while (post_length > 0)
        {
            char x = 'g';
            int bx =  read(0, &x, 1);
            if (bx == -1)
                std::cerr << strerror(errno) << std::endl;

            paramenter.push_back(x);
            post_length--;
        }
    }
 
    //2.解析正文，并给予运算。这里只用输出一个数来表示CGI结果
    //这里约定协议为：blog_id=1002
    std::string  key = paramenter.substr(paramenter.find('=') + 1);
    //登录连接数据库
    MYSQL *conn;
    MYSQL_RES *res_title;

    const char *server = "139.9.104.185";
    const char *user = "afeng";
    const char *password = "hxf17377795861";
    const char *database = "blog_system";
    conn = mysql_init(NULL);

    if (!mysql_real_connect(conn, server, user, password, database, 0, NULL, 0)) {
        std::cerr << mysql_error(conn) << std::endl;
        mysql_close(conn);
        return 1;
    }
    mysql_set_character_set(conn, "utf8");
    // 指令
    std::string str = "delete  from blog where blogId=";
    str += key;
    if (mysql_query(conn, str.c_str())) {
        std::cerr << mysql_error(conn) << std::endl;
        mysql_close(conn);
        return 1;
    }
    
    std::string body = "<p>success</p>";
    // std::cerr << "向父进程发送正文" << std::endl;
    std::cout << "Content-Type: text/html; charset=utf-8\r\r"; 
    // 向父进程发送正文
    std::cout << body << std::endl;//设置终止符

    mysql_free_result(res_title);
    mysql_close(conn);

    //马上退出，有没有都差不多
    if (methon == "POST")
    {
        close(1);
        close(0);
    }
    return 0;
}